@tool
class_name SpellButton
extends Range

const PROG_NAME = &"progress"

@export var switch_threshold: float = 0.4

@onready var _tex: TextureRect = $Texture
@onready var _orbit: Control = $Texture/Orbit
@onready var _prog: Range = $SwitchProg

@onready var _prog_threshold: float = 0.4 * switch_threshold

var texture: Texture2D:
	get:
		return _tex.texture
	set(val):
		_tex.texture = val

var is_on:
	get:
		return _orbit.visible
	set(val):
		_orbit.visible = val
		on_switch.emit(_orbit.visible)

signal on_click
signal on_secondary_click
signal on_switch(is_on: bool)

var _press_time: float = -1

func _ready() -> void:
	set_process(false)


func _gui_input(event: InputEvent) -> void:
	if event is InputEventMouseButton:
		if event.button_index == MOUSE_BUTTON_RIGHT:
			if event.pressed:
				# is_on = !is_on
				on_secondary_click.emit()
		elif event.button_index == MOUSE_BUTTON_LEFT:
			if event.pressed:
				if value == max_value:
					_tex.self_modulate = Color.GRAY
				_press_time = 0
				set_process(true)
			else:
				var is_click := _press_time < switch_threshold
				if value == max_value:
					if is_click:
						on_click.emit()
					_tex.self_modulate = Color.WHITE
				if !is_click:
					# is_on = !is_on
					on_secondary_click.emit()
				_press_time = -1
				_prog.visible = false
				set_process(false)


func _process(delta: float) -> void:
	if _press_time < _prog_threshold and _press_time + delta >= _prog_threshold:
		_prog.visible = true
		_prog.max_value = 100

	_press_time += delta
	
	if _press_time >= _prog_threshold:
		# 0.1 is tolerance
		_prog.value = (_press_time / switch_threshold - 0.1) * _prog.max_value


func _value_changed(new_value: float) -> void:
	if _press_time > 0 and new_value < max_value:
		_tex.self_modulate = Color.WHITE
	
	_tex.material.set_shader_parameter(PROG_NAME, new_value / max_value)


func turn_switch_no_signal(v: bool):
	_orbit.visible = v
